import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/udt_tb_workreportrecord_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/udt_tb_workreportrecord.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/pages/common/date_time_select.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_workreportrecordsearch/udt_tb_workreportrecordsearch_dialog.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

class UdtTbWorkreportrecordsearchList extends StatefulWidget {
  UdtTbWorkreportrecordsearchList({Key? key}) : super(key: key);

  @override
  _UdtTbWorkreportrecordsearchListState createState() =>
      _UdtTbWorkreportrecordsearchListState();
}

class _UdtTbWorkreportrecordsearchListState
    extends State<UdtTbWorkreportrecordsearchList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  UdtTbWorkreportrecord udtTbWorkreportrecord = UdtTbWorkreportrecord();
  List<UdtTbWorkreportrecord> selectedList = [];

  //车间
  List<SelectOptionVO> workshopList = [];

  //工位
  List<SelectOptionVO> stationList = [];

  //报工人员
  late List<SelectOptionVO> reportworkerList = [];

  UserInfo userInfo = StoreUtil.getCurrentUserInfo();

  DateFormat format = DateFormat('yyyy-MM-dd HH:mm:ss');

  @override
  void initState() {
    _loadSelectVO();
    super.initState();
    udtTbWorkreportrecord.reportDateStart = Utils.getDate()+" 00:00:00";
    udtTbWorkreportrecord.reportDateEnd = Utils.getDate()+" 23:59:59";
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  _loadSelectVO() async {
    if (userInfo.major != null) {
      workshopList = await DynamicDataApi.getModelSelect(
          model: "hr.department",
          name: "complete_name",
          key: "parent_id",
          operator: "!=",
          val: null);
    } else {
      stationList = await DynamicDataApi.getModelSelect(
          model: "base.productionstation",
          name: "stationname",
          key: 'workshop_id',
          val: int.parse(userInfo.deptId!));
      udtTbWorkreportrecord.workshopId = userInfo.deptId;
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    UserInfo userInfo = StoreUtil.getCurrentUserInfo();
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          userInfo.major != null
              ? CrySelect(
                  width: 280,
                  label: '生产车间',
                  dataList: workshopList,
                  value: udtTbWorkreportrecord.workshopId,
                  onSaved: (v) {
                    udtTbWorkreportrecord.workshopId = v;
                  },
                  onChange: (v) async {
                    if (udtTbWorkreportrecord.workshopId != v) {
                      formKey.currentState!.save();
                      udtTbWorkreportrecord.workshopId = v;
                      udtTbWorkreportrecord.stationId = null;
                      try {
                        stationList = await DynamicDataApi.getModelSelect(
                            model: "base.productionstation",
                            name: "stationname",
                            key: 'workshop_id',
                            val: int.parse(v));
                      } catch (e) {
                        stationList = [];
                      }
                      setState(() {});
                    }
                  },
                )
              : CryInput(
                  width: 200,
                  label: '生产车间',
                  enable: false,
                  value: userInfo.deptName,
                ),
          CrySelect(
            width: 280,
            label: '设备工位',
            dataList: stationList,
            value: udtTbWorkreportrecord.stationId,
            onSaved: (v) {
              udtTbWorkreportrecord.stationId = v;
            },
          ),
          CryInput(
            width: 160,
            label: '产品名称',
            value: udtTbWorkreportrecord.productName,
            onSaved: (v) {
              udtTbWorkreportrecord.productName = v;
            },
          ),
          DateTimeSelect(
            context,
            width: 230,
            label: '报工开始时间',
            value: udtTbWorkreportrecord.reportDateStart,
            lastDate: isNotBlank(udtTbWorkreportrecord.reportDateEnd)
                ? format.parse(udtTbWorkreportrecord.reportDateEnd!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              udtTbWorkreportrecord.reportDateStart = v;
              setState(() {});
            },
            onSaved: (v) {
              udtTbWorkreportrecord.reportDateStart = v;
            },
          ),
          DateTimeSelect(
            context,
            width: 230,
            label: '报工结束时间',
            value: udtTbWorkreportrecord.reportDateEnd,
            firstDate: isNotBlank(udtTbWorkreportrecord.reportDateStart)
                ? format.parse(udtTbWorkreportrecord.reportDateStart!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              udtTbWorkreportrecord.reportDateEnd = v;
              setState(() {});
            },
            onSaved: (v) {
              udtTbWorkreportrecord.reportDateEnd = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('工厂名称')),
        DataColumn(label: Text('车间名称')),
        DataColumn(label: Text('生产单号')),
        DataColumn(label: Text('产品图号')),
        DataColumn(label: Text('产品名称')),
        DataColumn(label: Text('材料型号')),
        DataColumn(label: Text('生产工序')),
        DataColumn(label: Text('换模个数')),
        DataColumn(label: Text('合格数量')),
        DataColumn(label: Text('不合格数量')),
        DataColumn(label: Text('备货数量')),
        DataColumn(label: Text('班次')),
        DataColumn(label: Text('班组名称')),
        DataColumn(label: Text('设备工位')),
        DataColumn(label: Text('报工人')),
        DataColumn(label: Text('报工日期')),
      ],
      getCells: (m) {
        UdtTbWorkreportrecord udtTbWorkreportrecord =
            UdtTbWorkreportrecord.fromMap(m);
        return [
          DataCell(Text(udtTbWorkreportrecord.factoryName ?? '--')),
          DataCell(Text(udtTbWorkreportrecord.workshopName ?? '--')),
          DataCell(Text(udtTbWorkreportrecord.productionorderno ?? '--')),
          DataCell(Text(udtTbWorkreportrecord.productCode ?? '--')),
          DataCell(Text(udtTbWorkreportrecord.productName ?? '--')),
          DataCell(Text(udtTbWorkreportrecord.spec ?? '--')),
          DataCell(Text(udtTbWorkreportrecord.processName ?? '--')),
          DataCell(Text((udtTbWorkreportrecord.replacenumber != null)
              ? udtTbWorkreportrecord.replacenumber.toString()
              : '--')),
          DataCell(Text((udtTbWorkreportrecord.qualifiedquantity != null)
              ? udtTbWorkreportrecord.qualifiedquantity.toString()
              : '--')),
          DataCell(Text((udtTbWorkreportrecord.unqualifiedquantity != null)
              ? udtTbWorkreportrecord.unqualifiedquantity.toString()
              : '--')),
          DataCell(Text((udtTbWorkreportrecord.repairquantity != null)
              ? udtTbWorkreportrecord.repairquantity.toString()
              : '--')),
          DataCell(Text(udtTbWorkreportrecord.shiftName ?? '--')),
          DataCell(Text(udtTbWorkreportrecord.teamName ?? '--')),
          DataCell(Text(udtTbWorkreportrecord.stationName ?? '--')),
          DataCell(Text(udtTbWorkreportrecord.reportworkerName ?? '--')),
          DataCell(Text(udtTbWorkreportrecord.reportDate ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButton(
          label: "导出",
          onPressed: selectedList.length != 0
              ? () => _generateExcel(selectedList)
              : null,
          iconData: Icons.import_export_outlined,
        )
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              isDisplayDesktop(context) ? form : Container(),
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: isDisplayDesktop(context) ? buttonBar : Container(),
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _reset() {
    udtTbWorkreportrecord = UdtTbWorkreportrecord();
    formKey.currentState!.reset();
    if (userInfo.major != null) {
      stationList = [];
    }
    udtTbWorkreportrecord.reportDateStart = Utils.getDate()+" 00:00:00";
    udtTbWorkreportrecord.reportDateEnd = Utils.getDate()+" 23:59:59";
    tableKey.currentState?.pageTo(0);
    // tableKey.currentState!.loadData(PageModel());
    setState(() {});
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    if (isBlank(udtTbWorkreportrecord.reportDateStart) ||
        isBlank(udtTbWorkreportrecord.reportDateEnd)) {
      tableKey.currentState?.pageTo(0);
      tableKey.currentState!.loadData(PageModel());
      CryUtils.message('请选择报工开始和结束时间');
      return;
    }
    var filter = {};
    if (isNotBlank(udtTbWorkreportrecord.productName)) {
      filter = {
        "product.template": [
          'product_id',
          ['name', 'like', '%${udtTbWorkreportrecord.productName}%']
        ]
      };
    }
    ResponseBodyApi responseBodyApi =
        await UdtTbWorkreportrecordOdooApi.page(data: {
      "page": page,
      "domainList": udtTbWorkreportrecord.toDomainList(),
      "filter": filter
    });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: UdtTbWorkreportrecordsearchDialog(),
      ),
    ).then((v) {
      if (v != null) {
        udtTbWorkreportrecord = v;
        _query();
      }
    });
  }

  _generateExcel(List<UdtTbWorkreportrecord> selectedList) {
    List<Map> map = [
      {
        'name': 'factoryName',
        'label': '工厂名称',
        'columnWidth': 10.0,
      },
      {
        'name': 'workshopName',
        'label': '车间名称',
        'columnWidth': 10.0,
      },
      {
        'name': 'productionorderno',
        'label': '生产单号',
        'columnWidth': 10.0,
      },
      {
        'name': 'productCode',
        'label': '产品图号',
        'columnWidth': 10.0,
      },
      {
        'name': 'productName',
        'label': '产品名称',
        'columnWidth': 10.0,
      },
      {
        'name': 'spec',
        'label': '材料型号',
        'columnWidth': 10.0,
      },
      {
        'name': 'replacenumber',
        'label': '换模个数',
        'columnWidth': 10.0,
      },
      {
        'name': 'qualifiedquantity',
        'label': '合格数量',
        'columnWidth': 10.0,
      },
      {
        'name': 'unqualifiedquantity',
        'label': '不合格数量',
        'columnWidth': 10.0,
      },
      {
        'name': 'repairquantity',
        'label': '备货数量',
        'columnWidth': 10.0,
      },
      {
        'name': 'shiftName',
        'label': '班次',
        'columnWidth': 10.0,
      },
      {
        'name': 'teamName',
        'label': '班组名称',
        'columnWidth': 10.0,
      },
      {
        'name': 'stationName',
        'label': '设备工位',
        'columnWidth': 10.0,
      },
      {
        'name': 'reportworkerName',
        'label': '报工人',
        'columnWidth': 10.0,
      },
      {
        'name': 'reportDate',
        'label': '报工日期',
        'columnWidth': 10.0,
      }
    ];
    Utils.generateExcel(
        fileName: "生产报工产量统计", configure: map, data: selectedList);
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<UdtTbWorkreportrecord>((e) => UdtTbWorkreportrecord.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.add) {
          _generateExcel(selectedList);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          enabled: selectedList.length != 0,
          child: ListTile(
            enabled: selectedList.length != 0,
            leading: const Icon(Icons.search),
            title: Text('导出'),
          ),
        ),
      ],
    );
  }
}
